package com.baox.agridata.synchronous.schedule;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baox.agridata.synchronous.constant.DataConstant;
import com.baox.agridata.synchronous.constant.HttpRequestUrl;
import com.baox.agridata.synchronous.constant.TaskNameConstant;
import com.baox.agridata.synchronous.entity.*;
import com.baox.agridata.synchronous.result.HttpResultResponse;
import com.baox.agridata.synchronous.result.Result;
import com.baox.agridata.synchronous.service.*;
import com.baox.agridata.synchronous.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 检疫证
 */

@Slf4j
@Component
public class SiChuanToChengDuSchedule {


    @Value("${TOCD.TCCAB}")
    private String AnimalBStartTime;

    @Value("${TOCD.TCCPB}")
    private String ProductBStartTime;


    @Value("${TOCD.TCCOutAA}")
    private String OutAnimalAStartTime;


    @Value("${TOCD.TCCOutPA}")
    private String OutProductAStartTime;


    @Value("${TOCD.TCheckPointResultTime}")
    private String TCheckPointResultTime;

    @Autowired
    private AsyncLogOperationService asyncLogOperationService;

    @Autowired
    private TCCABService tccabService;

    @Autowired
    private TCCPBService tccpbService;

    @Autowired
    private TCCOutAAService tccOutAAService;

    @Autowired
    private TCCOutPAService tccOutPAService;

    @Autowired
    private TCheckPointResultService tCheckPointResultService;


    @Autowired
    private ScAgricultureTaskService scAgricultureTaskService;


    /**
     * 动物B：四川到成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void synchronizationTCCABToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_AB);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【四川到成都动物B】开始同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "AnimalB";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "AnimalB";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    AnimalBStartTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(AnimalBStartTime) || "null".equals(AnimalBStartTime)) {
                        AnimalBStartTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCABEntity> l_list = tccabService.selectTCCABDataToChengDu(AnimalBStartTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.ANIMAL_B);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        //发送成功后，将新的时间重新写入文件中，下次读取
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【四川到成都动物B】文件记录生成状态：{},文件读取内容为：{},记录内容为：{},发送成都的条目数为：{}", timeCreateStatus, AnimalBStartTime, nowTime, l_list.size());

                        List<String> factoryCodeList = l_list.stream().map(TCCABEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, AnimalBStartTime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.error("【四川到成都动物B】network error，时间节点为：{}---{}", AnimalBStartTime, nowTime);
                    }
                } else {
                    log.info("【四川到成都动物B】本次未查询到数据，时间节点为：{}---{}", AnimalBStartTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                }
            } catch (Exception e) {
                log.info("T_CC_AB 出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【四川到成都动物B】同步任务未开启");
        }
    }

    /**
     * 产品B：四川到成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void synchronizationTCCPBToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_PB);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【四川到成都产品B】开始同步");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "ProductB";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "ProductB";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    ProductBStartTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(ProductBStartTime) || "null".equals(ProductBStartTime)) {
                        ProductBStartTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCPBEntity> l_list = tccpbService.selectTCCPBDataToChengDu(ProductBStartTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.PRODUCT_B);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        //发送成功后，将新的时间重新写入文件中，下次读取
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【四川到成都产品B】文件记录生成状态：{},文件读取内容：{},文件记录内容：{},发送成都的条目数为：{}", timeCreateStatus, ProductBStartTime, nowTime, l_list.size());

                        List<String> factoryCodeList = l_list.stream().map(TCCPBEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, ProductBStartTime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.info("【四川到成都产品B】network error，时间节点为：{}---{}", ProductBStartTime, nowTime);
                    }
                } else {
                    log.info("【四川到成都产品B】本次未查询到数据，时间节点为：{}---{}", ProductBStartTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                }
            } catch (Exception e) {
                log.info("T_CC_PB 出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【四川到成都产品B】同步任务未开启");
        }
    }


    /**
     * 外省动物A：四川到成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void synchronizationTCCOutAAToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_Out_AA);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【四川到成都外省动物A目的地为成都】同步任务开始");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "OutAnimalAA";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "OutAnimalAA";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    OutAnimalAStartTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(OutAnimalAStartTime) || "null".equals(OutAnimalAStartTime)) {
                        OutAnimalAStartTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCOutAAEntity> l_list = tccOutAAService.selectTCCOutAADataToChengDu(OutAnimalAStartTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.OUT_ANIMAL_A);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        //发送成功后，将新的时间重新写入文件中，下次读取
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【四川到成都外省动物A】文件记录生成状态：{},文件读取内容：{},文件记录内容：{},发送成都的条目数为：{}", timeCreateStatus, OutAnimalAStartTime, nowTime, l_list.size());

                        List<String> factoryCodeList = l_list.stream().map(TCCOutAAEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, OutAnimalAStartTime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.info("【四川到成都外省动物A】network error，时间节点为：{}---{}", OutAnimalAStartTime, nowTime);
                    }
                } else {
                    log.info("【四川到成都外省动物A】本次未查询到数据，时间节点为：{}---{}", OutAnimalAStartTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                }
            } catch (Exception e) {
                log.info("TCC_Out_AA 出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【四川到成都外省动物A目的地为成都】同步任务未开启");
        }
    }


    /**
     * 外省产品A：四川到成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0/5 * * * ?")
    public void synchronizationTCCOutPAToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CC_Out_PA);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【四川到成都外省产品A目的地为成都】同步任务开始");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "OutProductPA";
                String l_filePath_record = l_file.getPath() + File.separator + "Record" + File.separator + "OutProductPA";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    OutProductAStartTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(OutProductAStartTime) || "null".equals(OutProductAStartTime)) {
                        OutProductAStartTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCCOutPAEntity> l_list = tccOutPAService.selectTCCOutPADataToChengDu(OutProductAStartTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.OUT_PRODUCT_A);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        //发送成功后，将新的时间重新写入文件中，下次读取
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【四川到成都外省产品A】文件记录生成状态：{},文件读取内容：{},文件记录内容：{},发送成都的条目数为：{}", timeCreateStatus, OutProductAStartTime, nowTime, l_list.size());

                        //---------------异步记录检疫证号-----------
                        List<String> factoryCodeList = l_list.stream().map(TCCOutPAEntity::getFactoryCode).collect(Collectors.toList()); //检疫证号记录数据
                        asyncLogOperationService.insertFactoryCodeRecord(factoryCodeList, OutProductAStartTime, nowTime, l_filePath_record);  //异步记录检疫证号
                    } else {
                        log.info("【四川到成都外省产品A】network error，时间节点为：{}---{}", OutProductAStartTime, nowTime);
                    }
                } else {
                    log.info("【四川到成都外省产品A】本次未查询到数据，时间节点为：{}---{}", OutProductAStartTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                }
            } catch (Exception e) {
                log.info("TCC_Out_PA 出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【四川到成都外省产品A目的地为成都】同步任务未开启");
        }
    }

    /**
     * 检查站检查结果到成都
     */
    @Async("newAsyncExecutor")
    @Scheduled(cron = "0 0 * * * ?")
    public void synchronizationCheckPointResultToChengdu() {
        ScAgricultureTask sxAgricultureTask = scAgricultureTaskService.selectTaskStatus(TaskNameConstant.T_CHECK_POINT_RESULT);
        if (sxAgricultureTask.getZt().intValue() == 1) {
            try {
                log.info("【四川到成都检查站检查结果到成都】同步任务开始");
                FileUtil l_file = new FileUtil();
                String l_filePath = l_file.getPath() + File.separator + "TaskConfig" + File.separator + "TCheckPointResult";
                String nowTime = DateUtil.jianOneMinutes() + ":00";
                ///读取最后一次同步数据的时间
                if (l_file.CheckFileExists(l_filePath, DataConstant.FILE_NAME)) {
                    TCheckPointResultTime = l_file.readLastLineV2(l_filePath, DataConstant.FILE_NAME);
                    if (StringUtils.isEmpty(TCheckPointResultTime) || "null".equals(TCheckPointResultTime)) {
                        TCheckPointResultTime = DateUtil.jianFiveMinutes(nowTime);
                    }
                }
                List<TCheckPointResultEntity> l_list = tCheckPointResultService.selectTCheckPointResult(TCheckPointResultTime, nowTime);
                if (l_list != null && l_list.stream().count() > 0) {
                    Integer resultCode = sendNetWorkData(l_list, HttpRequestUrl.T_CHECK_POINT_RESULT);
                    if (resultCode.intValue() == Result.ok().getCode()) {  //当发送成功后，继续后续的操作
                        //发送成功后，将新的时间重新写入文件中，下次读取
                        boolean timeCreateStatus = l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                        log.info("【四川到成都检查站检查结果到成都】文件记录生成状态：{},文件读取内容：{},文件记录内容：{},发送成都的条目数为：{}", timeCreateStatus, TCheckPointResultTime, nowTime, l_list.size());
                    } else {
                        log.info("【四川到成都检查站检查结果到成都】network error，时间节点为：{}---{}", TCheckPointResultTime, nowTime);
                    }
                } else {
                    log.info("【四川到成都检查站检查结果到成都】本次未查询到数据，时间节点为：{}---{}", TCheckPointResultTime, nowTime);
                    l_file.WriteContent(nowTime, l_filePath, DataConstant.FILE_NAME);
                }
            } catch (Exception e) {
                log.info("TCheck_Point_Result 出现了错误：" + e.getMessage());
            }
        } else {
            log.info("【四川到成都检查站检查结果到成都】同步任务未开启");
        }
    }


    /**
     * 匹配网络请求
     *
     * @param obj
     * @param requestUrl
     * @return
     */
    private Integer sendNetWorkData(List<?> obj, String requestUrl) {
        Integer resultCode = 0;
        try {
            String jsonData = JSON.toJSONString(obj);
            byte[] gzipData = GZIPUtils.compress(jsonData); //开始压缩
            HttpResultResponse result = HttpUtils.post(requestUrl, gzipData, HttpUtils.headers);  //发送网络请求
            JSONObject jsonObject = JSON.parseObject(result.getBody());
            resultCode = jsonObject.getInteger("code");
        } catch (Exception e) {
            e.printStackTrace();
            return resultCode;
        }
        return resultCode;
    }


}
